<template>
  <div>
    <h2 style="font-size: 20px;padding-left: 25px;">欢迎使用裕酷门店管理系统</h2>
    <van-form @submit="onSubmit">
      <van-field v-model="userName" required name="userName" label="账号" placeholder="账号"
        :rules="[{ required: true, message: '请填写账号' }]" />
      <van-field v-model="password" required type="password" name="password" label="密码" placeholder="密码"
        :rules="[{ required: true, message: '请填写密码' }]" />
      <van-field v-model="code" center required clearable name="code" label="验证码" placeholder="请输入验证码"
        :rules="[{ required: true, message: '请填写密码' }]">
        <template #button>
          <img :src="imgSrc" style="width: 100px;height: 30px;display: block" @click="getImgId">
        </template>
      </van-field>
      <div style="margin: 16px;">
        <van-button round block type="info" native-type="submit">提交</van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import { getImgId, getImg, login, checkImg } from '@/api/user'
import md5 from 'md5';
import { Toast } from 'vant';
export default {
  name: "Login",
  data() {
    return {
      userName: '',
      password: '',
      code: '',
      imgId: '',
      imgSrc: '',
      error: false
    }
  },
  mounted() {
    this.getImgId();
  },
  methods: {
    async getImgId() {
      let res = await getImgId();
      if (res.code === 200) {
        this.imgId = res.data;
        this.getImg();
      }
    },
    async getImg() {
      let res = await getImg(this.imgId);
      this.imgSrc = URL.createObjectURL(res);
    },
    onSubmit(value) {
      this.login(value)
    },
    async login(data) {
      // 先验证验证码
      let { userName, password: password1, code } = data;
      try {
        const res = await checkImg({
          captchaKey: this.imgId,
          captchaValue: code,
        })
        if (res.code === 200) {
          const password = md5(password1);


          this.$store.dispatch("user/login", {
            userName,
            password,
          }).then((res) => {
            if (res !== 200) {
              setTimeout(() => {
                this.getImgId();
              }, 1000)
            }
            this.$router.push("/");
          }).catch(() => {
            setTimeout(() => {
              this.getImgId();
            }, 1000)
          });
        } else {
          setTimeout(() => {
            this.getImgId();
          }, 1000)
        }
      } catch (error) {
        setTimeout(() => {
          this.getImgId();
        }, 1000)
      }


    }
  },
}
</script>

<style lang="scss" scoped></style>